<template>
  <div class="articleList">
    <van-pull-refresh
    :success-duration="1500"
    :success-text="pullRefreshText"
    v-model="isPullLoading"
    @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem
        v-for="item in list"
        :key="item.art_id + ''"
        :articleItem="item"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import { Toast } from 'vant'
import ArticleItem from '@/components/articleItem.vue'
export default {
  data () {
    return {
      list: [],
      loading: false, // 是否在加载中
      finished: false, // 数据是否已经全部加载完成
      preTimestamp: Date.now(),
      error: false, // 控制错误提示
      isPullLoading: false,
      pullRefreshText: ''
    }
  },

  components: {
    ArticleItem
  },

  props: {
    channelId: {
      type: Number,
      required: true
    }
  },

  created () {

  },

  methods: {
    // 列表初次显示
    // 加载的数据不能显示一整屏
    // 触底时候
    async onLoad () {
      // 1. 发送求获取数据
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.preTimestamp,
          with_top: 1
        })
        // if (Math.random() > 0.2) {
        //   console.lg('13')
        // }
        // console.log(res)
        // 2. 保存数据
        this.list.push(...res.results)
        this.preTimestamp = res.pre_timestamp
        // 3. 加载状态结束
        this.loading = false
        // 4. 数据全部加载完成
        if (!res.pre_timestamp) {
          // 代表时间戳返回null
          this.finished = true
        }
      } catch (err) {
        Toast.clear()
        this.loading = false
        // 一旦显示错误提示 load终止不在触发 点击错误文本会再次触发
        this.error = true
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.8) {
          console.lg(1)
        }
        console.log(res)
        this.isPullLoading = false
        this.list.unshift(...res.results)
        this.pullRefreshText = '亲,共刷新' + res.results.length + '条数据'
      } catch (err) {
        // console.log('出错了')
        this.isPullLoading = false
        this.pullRefreshText = '亲,网络异常,稍后重试'
      }
    }
  }
}
</script>

<style scoped lang="less">
// vw vh 视口单位
// 正常 视口 = 手机屏幕
.articleList {
  height: 80vh;
  overflow-y: scroll;
}
</style>
